<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Default_Model_ProductKey extends Zend_Db_Table{
	
	protected $_name    = "product_keys";
    protected $_primary = "id";
    
    public function saveOrderKeys($key_id, $order_id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $data['order'] = $order_id;
            $data['key'] = $key_id;
            
            $db->insert("order_keys", $data);
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function getData($id){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $select = $db->select()
                    ->from(array('p' => 'product_keys'), array('id', 'key', 'product_id'))
                    ->join(array('pr' => 'products'), "pr.id = p.product_id", array('name'))
                    ->where('p.status = 0')
                    ->where('p.product_id = ?', $id, 'INTEGER')
                    ->order('p.id');
        
        $result = $db->fetchRow($select);
        
        return $result;
    }
    
    public function getUsedKeys($order_id){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        $select = $db->select()
                    ->from(array('ok' => 'order_keys'), array('id', 'order'))
                    ->join(array('pk' => 'product_keys'), "pk.id = ok.key", array('key'))
                    ->join(array('p' => 'products'), "p.id = pk.product_id", array('name'))
                    ->where('ok.order = ?', $order_id, "INTEGER")
                    ->order('ok.id');
        
        $result = $db->fetchAll($select);
        
        return $result;
    }
    
    public function updateStatus($id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $data['status'] = true;
            $data['id'] = $id;
            
            $db->update("product_keys", $data, "id = $id");
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'product_keys', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}